import React from 'react';

class WarnBar extends React.Component {

    constructor(props) {
        super(props);
    }

    toggle() {
        this.props.onWarnClick(this.props.name);
    }

    render() {
        if (this.props.active && this.props.name !== this.props.active) {
            alert(this.props.name + "收到来自" + this.props.active + "的警报");
        }
        return (
            <button onClick={this.toggle.bind(this)}>{this.props.name}</button>
    );
    }
}

class ChildClock extends React.Component {
    render() {
        return (
            <h2>child is {this.props.date.toLocaleTimeString()}.</h2>
    );
    }
}

export default class Clock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            num: 0,
            date: new Date(),
            activeWarn: false
        };
        this.alterNum2 = this.alterNum2.bind(this);
        this.warns = ["警报1", "警报2", "警报3"];
    }

    componentDidMount() {
        // this.timeID = setInterval(() => this.tick(), 1000);
        //注意:不能用这个 this.timeID = setInterval(this.tick, 1000);否则,this.setState的this就不是Clock对象
    }

    componentWillUnMount() {
        clearInterval(this.timeID);
    }

    tick() {
        this.setState(({date, num, toggleFlag}) => ({
            date: new Date(),
            num: num + 1,
            activeWarn: false
        }));
    }

    alterNum = ({num = this.state.num}) => {
    alert(num);
}

alterNum2() {
    alert(this.state.num);
}

alterNum3() {
    alert(this.state.num);
}

toggleWarn(name) {
    this.setState(preState => ({
        date: new Date(),
        num: preState.num + 1,
        activeWarn: name
    }));
}

render() {
    return (
        <div>
        <h1>hello world</h1>
    <h2>parent is {this.state.date.toLocaleTimeString()}.</h2>
    <ChildClock date={this.state.date}/>
    {/*通过属性初始化器语法绑定this*/}
<button onClick={this.alterNum}>提示1</button>
    {/*通过method.bind绑定this*/}
<button onClick={this.alterNum2}>提示2</button>
    {/*通过箭头函数绑定this(不推荐)*/}
<button onClick={() => this.alterNum3()}>提示3</button>
    <br/>
    {/*列表渲染*/}
    {this.warns.map(n => {
        return (<WarnBar key={n} name={n} onWarnClick={this.toggleWarn.bind(this)}
        active={this.state.activeWarn}/>)
    })}
</div>
);
}
}
